package com.aiserver.service.impl;

import com.aiserver.entity.User;
import com.aiserver.service.WechatService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 微信服务实现类
 */
@Service
public class WechatServiceImpl implements WechatService {

    private static final Logger logger = LoggerFactory.getLogger(WechatServiceImpl.class);

    @Value("${app.wechat.app-id}")
    private String appId;

    @Value("${app.wechat.app-secret}")
    private String appSecret;

    @Value("${app.wechat.redirect-uri}")
    private String redirectUri;

    // 微信API地址
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    private static final String AUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";

    @Override
    public User getUserInfoByCode(String code) {
        try {
            // 1. 通过code获取access_token
            String accessTokenResponse = getAccessToken(code);
            JSONObject tokenJson = JSON.parseObject(accessTokenResponse);
            
            if (tokenJson.containsKey("errcode")) {
                throw new RuntimeException("获取微信access_token失败: " + tokenJson.getString("errmsg"));
            }
            
            String accessToken = tokenJson.getString("access_token");
            String openId = tokenJson.getString("openid");
            String unionId = tokenJson.getString("unionid");
            
            // 2. 通过access_token获取用户信息
            User user = getUserInfo(accessToken, openId);
            user.setWechatUnionId(unionId);
            
            return user;
        } catch (Exception e) {
            logger.error("获取微信用户信息失败", e);
            throw new RuntimeException("获取微信用户信息失败: " + e.getMessage());
        }
    }

    @Override
    public String getAccessToken(String code) {
        String url = ACCESS_TOKEN_URL + 
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        
        return httpGet(url);
    }

    @Override
    public User getUserInfo(String accessToken, String openId) {
        String url = USER_INFO_URL + 
                "?access_token=" + accessToken +
                "&openid=" + openId +
                "&lang=zh_CN";
        
        String response = httpGet(url);
        JSONObject userJson = JSON.parseObject(response);
        
        if (userJson.containsKey("errcode")) {
            throw new RuntimeException("获取微信用户信息失败: " + userJson.getString("errmsg"));
        }
        
        User user = new User();
        user.setWechatOpenId(userJson.getString("openid"));
        user.setNickname(userJson.getString("nickname"));
        user.setAvatar(userJson.getString("headimgurl"));
        
        return user;
    }

    @Override
    public String generateAuthUrl(String state) {
        try {
            String encodedRedirectUri = URLEncoder.encode(redirectUri, StandardCharsets.UTF_8.toString());
            return AUTH_URL + 
                    "?appid=" + appId +
                    "&redirect_uri=" + encodedRedirectUri +
                    "&response_type=code" +
                    "&scope=snsapi_userinfo" +
                    "&state=" + (state != null ? state : "STATE") +
                    "#wechat_redirect";
        } catch (Exception e) {
            logger.error("生成微信授权URL失败", e);
            throw new RuntimeException("生成微信授权URL失败");
        }
    }

    /**
     * 发送HTTP GET请求
     */
    private String httpGet(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("User-Agent", "Mozilla/5.0");
            
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (IOException e) {
            logger.error("HTTP请求失败: {}", url, e);
            throw new RuntimeException("HTTP请求失败: " + e.getMessage());
        }
    }
}